﻿(function ($) {

    $.util.namespace("mainpage");
    $.util.namespace("mainpage.mainTabs");

    var homeLayout = "#home-layout", nowTimeLabelId = "#nowTime", northTopbar = "#north-topbar", northToolbar = "#north-toolbar",
        westAccordion = "#menu-accordion1", eastAccordion = "#menu-accordion2",
        homePageTitle = "主页", homePageHref = null, mainTab = "#mainTab", homePanel = "#homePanel";

    //刷新屏幕右上角的当前时间显示的标签。
    window.mainpage.beginAutoRefreshNowTimeLabel = function () {
        var refresh = function () { $(nowTimeLabelId).text($.date.toLongDateTimeString(new Date())); };
        refresh();
        window.setInterval(refresh, 1000);
    };

    //绑定主界面工具栏按钮事件。
    window.mainpage.bindMainFormButtonBarEvent = function () {

        //重新计算portal的尺寸 未实现，原因是panel的折叠、展开事件有bug
        var resizePortal = function () {
            if (window.deskIndex && $.isFunction(window.deskIndex.resizePortal)) {
                window.deskIndex.resizePortal(true);
            }
        };

        //隐藏顶部栏按钮事件
        $("#btnHideNorth").click(function () { window.mainpage.hideNorth(); });
        //显示顶部栏按钮事件
        var btnShow = $("#btnShowNorth").click(function () { window.mainpage.showNorth(); });
        var north = $(homeLayout).layout("panel", "north"), panel = north.panel("panel"),
            toolbar = $(northToolbar), topbar = $(northTopbar), top = toolbar.css("top"),
            opts = north.panel("options"), onCollapse = opts.onCollapse, onExpand = opts.onExpand;

        opts.onCollapse = function () {
            if ($.isFunction(onCollapse)) { onCollapse.apply(this, arguments); }
            btnShow.show();
            toolbar.insertBefore(panel).css("top", 0).removeClass("panel-header-self").addClass("panel-header top-toolbar-topmost");
            resizePortal();
        };
        opts.onExpand = function () {
            if ($.isFunction(onExpand)) { onExpand.apply(this, arguments); }
            btnShow.hide();
            toolbar.insertAfter(topbar).css("top", top).addClass("panel-header-self").removeClass("panel-header top-toolbar-topmost");
            resizePortal();
        };

        
        var west = $(homeLayout).layout("panel", "west"), westOpts = west.panel("options");
        westOpts.onExpand = resizePortal;
        westOpts.onCollapse = resizePortal;
    };

    window.mainpage.hideNorth = function () { $(homeLayout).layout("collapse", "north"); };

    window.mainpage.showNorth = function () { $(homeLayout).layout("expand", "north"); };



    //  初始化应用程序主界面左侧面板中“导航菜单”的数据，并加载特定的子菜单树数据。
    window.mainpage.instMainMenus = function (rootMenuId) {
        window.mainpage.loadNavMenus(rootMenuId);
    };

    //  将指定的根节点数据集合数据加载至两侧面板中“菜单导航栏”的 accordion 控件中；该方法定义如下参数：
    //      rootMenuId: 默认打开的主功能菜单ID值
    window.mainpage.loadNavMenus = function (rootMenuId) {
        var accor1 = $(westAccordion).empty(), accor2 = $(eastAccordion).empty();
        window.mainpage.authmenus.getWestRootMenus(function (data) {
            $.each(data, function (i, item) {
                var p = $("<div />").attr({
                    "data-options": "border:false, title:'" + item.text + "', iconCls:'" + item.iconCls + "', selected:" + (item.id == rootMenuId ? true : false) + ", bodyCls:'bottomBorder1px treeSpace'",
                    key: item.id, keycode: item.code
                });
                p.css({ padding: "10px;" }).appendTo(accor1);
                $("<ul />").attr({ id: item.id + "-menu-tree" }).appendTo(p);
            });

            accor1.accordion({
                fit: true, border: true, animate: true,
                onSelect: function (title, index) {
                    //先获取当前panel对应的菜单信息
                    var currentPanel = $(this).accordion("getSelected"), key = currentPanel.attr("key"), keyCode = currentPanel.attr("keycode");
                    //判定panel中的ul是否已经是tree，如果还未初始化则把ul初始化成tree，如果已经是tree，则loadData
                    var insideTree = $("#" + key + "-menu-tree");
                    if (insideTree.length == 1) {
                        var state = $.data(insideTree[0], "tree"), inited = state && state.options ? true : false;
                        if (!inited) {
                            window.mainpage.instNavTree(insideTree);
                        }
                        //加载tree数据
                        window.mainpage.loadMenu(insideTree, key, keyCode);
                    }
                }
            });
        });

        window.mainpage.authmenus.getEastRootMenus(function (data) {
            $.each(data, function (i, item) {
                var p = $("<div />").attr({
                    "data-options": "border:false, title:'" + item.text + "', iconCls:'" + item.iconCls + "', selected:" + (item.id == rootMenuId ? true : false) + ", bodyCls:'bottomBorder1px treeSpace'",
                    key: item.id, keycode: item.code
                });
                p.css({ padding: "10px;" }).appendTo(accor2);
                $("<ul />").attr({ id: item.id + "-menu-tree" }).appendTo(p);
            });

            accor2.accordion({
                fit: true, border: true, animate: true,
                onSelect: function (title, index) {
                    //先获取当前panel对应的菜单信息
                    var currentPanel = $(this).accordion("getSelected"), key = currentPanel.attr("key"), keyCode = currentPanel.attr("keycode");
                    //判定panel中的ul是否已经是tree，如果还未初始化则把ul初始化成tree，如果已经是tree，则loadData
                    var insideTree = $("#" + key + "-menu-tree");
                    if (insideTree.length == 1) {
                        var state = $.data(insideTree[0], "tree"), inited = state && state.options ? true : false;
                        if (!inited) {
                            window.mainpage.instNavTree(insideTree);
                        }
                        //加载tree数据
                        window.mainpage.loadMenu(insideTree, key, keyCode);
                    }
                }
            });
        });
    };

    //  初始化 westAccordionPanel 位置的 ul 控件(仅初始化 easyui-tree 对象，不加载数据)。
    window.mainpage.instNavTree = function (treeDom) {
        var t = treeDom.tree({
            animate: true,
            lines: false,
            onClick: function (node) {
                if (!node || !node.attributes || !node.attributes.module || $.string.isNullOrWhiteSpace(node.attributes.module)) { return; }
                var href = "/Public/ExampleIndex?" + $.param({ module: node.attributes.module, extension: node.attributes.extension });
                window.mainpage.mainTabs.addModule(node.text, href, node.iconCls, true);
            }
        });
    };

    //  按照指定的根节点菜单 id，加载其相应的子菜单树面板数据；该方法定义如下参数：
    //      tree: 表示要loadData的tree控件的jq对象
    //      id: 表示根节点菜单的 id；
    //      code: 表示根节点菜单的 code
    window.mainpage.loadMenu = function (tree, id, code) {
        window.mainpage.authmenus.getChildrenMenus(id, code, function (data) {
            tree.tree("loadData", data);
        });
    };



    //添加主页tab
    window.mainpage.addMainTab = function () {
        $(mainTab).tabs("add", { title: "主页", iconCls: "icon-hamburg-home", href: "/Home/PortalTestIndex" });
    };

    window.mainpage.mainTabs.tabDefaultOption = {
        title: "新建选项卡", href: "", closable: true, iconCls: "icon-standard-tab"
    };
    window.mainpage.mainTabs.parseCreateTabArgs = function (args) {
        var ret = {};
        if (args.length == 0) { $.extend(ret, window.mainpage.mainTabs.tabDefaultOption); }
        if (args.length == 1) { $.extend(ret, window.mainpage.mainTabs.tabDefaultOption, typeof args[0] == "object" ? args[0] : { href: args[0] }); }
        if (args.length == 2) { $.extend(ret, window.mainpage.mainTabs.tabDefaultOption, { title: args[0], href: args[1] }); }
        if (args.length == 3) { $.extend(ret, window.mainpage.mainTabs.tabDefaultOption, { title: args[0], href: args[1], iconCls: args[2] }); }
        if (args.length == 4) { $.extend(ret, window.mainpage.mainTabs.tabDefaultOption, { title: args[0], href: args[1], iconCls: args[2], closable: args[3] }); }
        if (ret.iconCls == "icon-unknow") { ret.iconCls = "icon-standard-tab" }

        return ret;
    };

    //  添加一个新的模块选项卡；该方法重载方式如下：
    //      function (tabOption)
    //      function (href)
    //      function (title, href)
    //      function (title, href, iconCls)
    //      function (title, href, iconCls, closable)
    window.mainpage.mainTabs.addModule = function (title, href, iconCls, closable) {
        var opts = window.mainpage.mainTabs.parseCreateTabArgs(arguments);
        //关闭“所有可关闭的标签页”
        var t = $(mainTab), tabs = t.tabs("tabs");
        for (var index = tabs.length - 1; index >= 0; index--) {
            var panelOpts = tabs[index].panel("options");
            if (panelOpts.closable == true && panelOpts.title != opts.title) { t.tabs("close", panelOpts.title); }
        }

        var isExists = window.mainpage.mainTabs.isExists(opts.title, opts.href);
        switch (isExists) {
            case 0:
                t.tabs("add", opts);
                break;
            case 1:
                //暂时以“打开新tab关闭旧tab”的方式显示新标签，故注释以下代码
                //var t = $(mainTab), i = undefined;
                //while (t.tabs("getTab", opts.title + (i ? String(i) : ""))) { if (i == undefined) { i = 0; } i++; }
                //opts.title = opts.title + "(" + i + ")";
                t.tabs("add", opts);
                break;
            case 2: window.mainpage.mainTabs.jumeTab(opts.title); break;
            default: break;
        }
    }

    //  判断指定的选项卡是否存在于当前主页面的选项卡组中；
    //  返回值：返回的值可能是以下几种：
    //      0:  表示不存在于当前选项卡组中；
    //      1:  表示仅 title 值存在于当前选项卡组中；
    //      2:  表示 title 和 href 都存在于当前选项卡组中；
    window.mainpage.mainTabs.isExists = function (title, href) {
        var t = $(mainTab), tabs = t.tabs("tabs"), array = $.array.map(tabs, function (val) { return val.panel("options"); }),
            list = $.array.filter(array, function (val) { return val.title == title; }), ret = list.length ? 1 : 0;
        if (ret && $.array.some(list, function (val) { return val.href == href; })) { ret = 2; }
        return ret;
    };

    window.mainpage.mainTabs.jumeTab = function (which) { $(mainTab).tabs("select", which); };



    window.startup = function () {

        window.mainpage.beginAutoRefreshNowTimeLabel();

        window.mainpage.bindMainFormButtonBarEvent();

        window.mainpage.instMainMenus();

        var layout = $(homeLayout);

        $.util.delay(function () {

            layout.removeClass("hidden").layout("resize");

            //window.mainpage.addMainTab();

            $("#maskContainer").remove();

            $("#btnHideNorth").click();
        });
    };

})(jQuery);